package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.dto.ScrollResult;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Blog;
import com.hmdp.entity.User;
import com.hmdp.mapper.BlogMapper;
import com.hmdp.service.IBlogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.SystemConstants;
import com.hmdp.utils.UserHolder;
import org.apache.tomcat.util.buf.StringUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

import static com.hmdp.utils.RedisConstants.BLOG_LIKED_KEY;
import static com.hmdp.utils.RedisConstants.FEED_KEY;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class BlogServiceImpl extends ServiceImpl<BlogMapper, Blog> implements IBlogService {

    @Resource
    private IUserService userService;

    private final StringRedisTemplate stringRedisTemplate;

    public BlogServiceImpl(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    @Override
    public Result queryHotBlog(Integer current) {
        // 根据用户查询
        Page<Blog> page = query()
                .orderByDesc("liked")
                .page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));
        // 获取当前页数据
        List<Blog> records = page.getRecords();
        // 查询用户
        records.forEach(record -> {
            this.getUserInformation(record);
            this.isBlogLiked(record);
        });
        return Result.ok(records);
    }

    @Override
    public Result queryBlogById(Long id) {
        //查看笔记信息。
        //需要的信息不仅仅包含笔记的内容，还要有发布笔记的用户的信息，比如说userId,user头像，userName
        Blog blog = getById(id);
        getUserInformation(blog);
        //查询用户是否点过赞
        isBlogLiked(blog);
        return Result.ok(blog);
    }


    /**
     * 查询点赞排行榜
     * @param id
     **/
    @Override
    public Result queryLikesById(Long id) {
        //查询redis将所有给该笔记点赞的用户的信息显示出来
        String key = BLOG_LIKED_KEY + id;
        //显示前5个点赞的用户信息即可。
        Set<String> userIds = stringRedisTemplate.opsForZSet().range(key, 0, 4);
        if(userIds == null || userIds.isEmpty()){
            return Result.ok();
        }
        //显示将String转换成Long
        List<Long> ids = userIds.stream().map(Long::valueOf).collect(Collectors.toList());
        String idStr = StrUtil.join(",",ids);
        List<UserDTO> userDTOs = userService.query().in("id",ids).last("order by field(id,"+idStr+")").list().
                stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());
        return Result.ok(userDTOs);
    }


    private void isBlogLiked(Blog blog) {
        UserDTO user = UserHolder.getUser();
        if(user == null){
            //查不到用户，说明未登录
            return ;
        }
        Long userId = user.getId();
        //2.判断该用户是否点过赞
        String key = BLOG_LIKED_KEY + blog.getId();
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        blog.setIsLike(score!=null);
    }

    private void getUserInformation(Blog blog) {
        Long userId = blog.getUserId();
        User user = userService.getById(userId);
        blog.setName(user.getNickName());
        blog.setIcon(user.getIcon());
    }

    /**
     * 实现笔记点赞功能
     * @param id
     **/
    @Override
    public Result likeBlog(Long id) {
        //点赞功能分析
        //不能无限点赞，第一次点赞，再点一次取消点赞。
        //使用属性isLike来表示一个笔记是否点过赞。
        //执行完下面逻辑之后还要在查询的时候修改isLike字段。

        //1.首先获得用户id
        UserDTO user = UserHolder.getUser();
        Long userId = user.getId();
        //2.判断该用户是否点过赞
        String key = BLOG_LIKED_KEY + id;
//        Boolean member = stringRedisTemplate.opsForSet().isMember(key, userId.toString());
        Double score = stringRedisTemplate.opsForZSet().score(key, userId.toString());
        if (score != null) {
            //3.若该用户点过赞，将该用户id从key的value集合中删除。并修改数据库字段like-1
            boolean isSuccess = update().setSql("liked = liked - 1").eq("id", id).update();
            if (isSuccess) {
                stringRedisTemplate.opsForZSet().remove(key, userId.toString());
            }
        } else {
            //4.若该用户没有点过赞，则将笔记Id和用户id放到redis中保存，笔记id作为key，value采用set方式，避免重复用户id。并修改数据库字段like+1
            boolean isSuccess = update().setSql("liked = liked + 1").eq("id", id).update();
            if (isSuccess) {
                //使用orderedSet存储点赞用户，这样可以进行排序，按照点赞时间进行。
                stringRedisTemplate.opsForZSet().add(key, userId.toString(), System.currentTimeMillis());
            }
        }
        return Result.ok();
    }


    /**
     * 滚动分页查询
     * @param max
     * @param offset
     **/
    @Override
    public Result queryBlogOfFollow(Long max, Integer offset) {
        //最终返回的数据包含List<Blog>,minTime(上一次查询的最小时间戳作为下一次查询的最大时间戳），offset（通过偏移量避免重复元素）
        //1.获取用户id
        Long userId = UserHolder.getUser().getId();
        //2.用户查询收件箱 ZREVRANGEBYSCORE key max min [WITHSCORES] [LIMIT offset count]
        String key = FEED_KEY + userId;
        //推送到收件箱里的数据取出来
        Set<ZSetOperations.TypedTuple<String>> typedTuples = stringRedisTemplate.opsForZSet().reverseRangeByScoreWithScores(key, 0, max, offset, 2);
        //3.非空判断
        if(typedTuples == null || typedTuples.isEmpty()){
            //3.1 如果收件箱没有推送笔记，直接返回空
            return Result.ok();
        }
        //4.解析数据：blogId,minTime(时间戳),offset
        List<Long> blogIds = new ArrayList<>(typedTuples.size());
        //最小时间戳
        long minTime = 0;
        //偏移量
        int os = 1;
        for (ZSetOperations.TypedTuple<String> tuple : typedTuples) {
            //4.1获取blogId
            blogIds.add(Long.valueOf(tuple.getValue()));
            //4.2 获取minTime
            long time = tuple.getScore().longValue();
            if(minTime == time){
                os++;
            }else{
                minTime = time;
                os = 1;
            }
        }
        //5.获取blog
        String idStr = StrUtil.join(",",blogIds);
        List<Blog> blogs = query().in("id", blogIds).last("order by field(id," + idStr + ")").list();  //last中的内容是拼接sql语句（字符串）  "order by field(id," + idStr + ")"
        for (Blog blog : blogs) {
            // 5.1.查询blog有关的用户
            getUserInformation(blog);
            // 5.2.查询blog是否被点赞
            isBlogLiked(blog);
        }

        ScrollResult scrollResult = new ScrollResult();
        scrollResult.setList(blogs);
        scrollResult.setMinTime(minTime);
        scrollResult.setOffset(os);
        return Result.ok(scrollResult);
    }
}
